<?php

class VacTag extends DataObject implements PermissionProvider
{
    private static $db = array(
        "TagCode" => "Varchar(10)",
        "VehicleNo" => "Varchar(10)",
        "TagStatus" => "Enum(array('active', 'deactivated', 'expired'))",
        "Expires" => "SS_Datetime"
    );

    private static $indexes = array(
        "TagCode_ID" => array("type" => "index", "value" => "TagCode, ID")
    );

    private static $has_one = array(
        "Resident" => "Resident",
        "QRFile" => "File"
    );

    public function canView($member = null)
    {
        return Permission::check(array(
            "ADMIN",
            "VIEW_VacTag"
        ), "any", $member);
    }

    public function canEdit($member = null)
    {
        return Permission::check(array(
            "ADMIN",
            "EDIT_VacTag"
        ), "any", $member);
    }

    public function canDelete($member = null)
    {
        return Permission::check(array(
            "ADMIN",
            "DELETE_VacTag"
        ), "any", $member);
    }

    public function FormattedTagStatus()
    {
        $this->isTagValid(false, false, $refStatus);

        if ($refStatus == "active") {
            return "Active";
        } elseif ($refStatus == "expired") {
            return "Expired";
        } else {
            return "Deactivated";
        }
    }

    public function getExpiryDatetime($datetime = null, $hour = 2, $useNiceFormat = false)
    {
        if ($datetime == null) {
            $datetime = SS_Datetime::now();
        }

        $dt = DateTime::createFromFormat("d/m/Y H:i", $datetime->now()->Nice24());
        $dt->add(new DateInterval("PT" . 60 * $hour . "M"));

        if ($useNiceFormat) {
            return $dt->format("d/m/Y H:i");
        } else {
            return $dt->format("Y-m-d H:i:s"); // MySQL datetime format.
        }
    }

    public function isTagValid($deactivateOnVerify = true, $sendNotificationOnVerifySuccess = false, &$refStatus = null)
    {
        $refStatus = $tagStatus = $this->obj("TagStatus");

        if ($tagStatus == Globals::STATUS_ACTIVE) {
            // Check whether is expired or not.
            $expires = $this->obj("Expires");

            if ($expires) {
                if ($expires <= SS_Datetime::now()) {
                    // Tag is already expired.
                    // Update TagStatus to: expired.
                    $refStatus = $this->TagStatus = Globals::STATUS_EXPIRED;
                    $this->write();
                } else {
                    if ($deactivateOnVerify) {
                        $this->TagStatus = Globals::STATUS_DEACTIVATED;
                        $this->write();

                        if ($sendNotificationOnVerifySuccess) {
                            SendVacNotification::sendNotification($this->Resident()->Username, "Visitor has arrived", "Visitor ref code: " . $this->TagCode . ($this->VehicleNo ? ", Vehicle No.: " . $this->VehicleNo : ""));
                        }
                    }

                    return true;
                }
            } else {
                // Expire date not set.
                // Should not happen. Which means record is broken.
                if ($this->TagStatus == Globals::STATUS_ACTIVE) {
                    $refStatus = $this->TagStatus = Globals::STATUS_DEACTIVATED;
                    $this->write();
                }
            }
        }

        return false;
    }

    public function generateQRFile()
    {
        $folder = Folder::find_or_make("/qr_codes/");
        $url = "http://chart.apis.google.com/chart?cht=qr&chs=150x150&chl=" . $this->TagCode . "&chld=H|0";
        $img = "assets/qr_codes/" . $this->TagCode . strtotime("now") . rand(1111, 9999) . ".png";

        DownloadFile::downloadFromUrl($url, BASE_PATH . "/" . $img);

        $file = new File();
        $file->Filename = $img;
        $file->ParentID = $folder->ID;
        $file->write();

        $this->QRFileID = $file->ID;
    }

    public function providePermissions()
    {
        $category = "Manage VAC tag permissions";

        return array(
            "VIEW_VacTag" => array(
                "name" => "View all records",
                "category" => $category
            ),
            "EDIT_VacTag" => array(
                "name" => "Edit record",
                "category" => $category
            ),
            "DELETE_VacTag" => array(
                "name" => "Delete record",
                "category" => $category
            )
        );
    }
}